<?php
	require_once("../libs/constants.php"); 
	require_once("../libs/classes/mysqlClass.php"); 
	require_once("../libs/functions/functions.php"); 
	require_once("../libs/functions/site_functions.php");
	require_once("../libs/functions/category_functions.php"); 
	require_once("../libs/functions/site_page_functions.php");
	require_once("../libs/functions/article_functions.php");
	require_once("../libs/functions/product_functions.php");
	require_once("../libs/functions/comment_functions.php");
	require_once("../libs/functions/account_functions.php");
	require_once("../libs/functions/cart_functions.php");
	require_once("../libs/functions/checkout_functions.php");
	
	require_once("functions/date_functions.php");
	
	
	define("SITE_TIMEZONE", 'UTC');
  	define("TIMEZONE_OFFSET", '+02:00');
 	define("W3C_DATETIME", 'Y-m-d\Th:i:s'); // See http://www.w3.org/TR/NOTE-datetime
	define("NULL_SITEMAP", '<urlset><url><loc></loc></url></urlset>');
	
	
	
	
	$site = verify_site(true);
	if($site == false)
	{
		return false;
	}
	
	$siteURL = scripts_url();
	define("URL_PREFIX", $siteURL);
	
	$articles = get_latest_articles(null, 0);
	
	$superCategories = get_category_hierarchy($_SESSION["language"]["id"]);
	
	$products = filter_products(false, false, null, 0, "id", "asc", false, false);
	
	$pages = get_site_pages();
	

	$sitemapFiles = array();
	
	$categories = array();
	$subCategories = array();
	$subCats = array();

	foreach($superCategories as $superKey => $supercat)
    {
    	if(isset($supercat["children"]))
		{
			foreach ($supercat["children"] as $catKey => $cat)
			{
				if(isset($cat["children"]))
				{
					foreach ($cat["children"] as $subCatKey => $subCat)
					{
						$subCats[$subCatKey]['url'] = URL_PREFIX . htmlspecialchars($subCat['url']);
			      		$subCats[$subCatKey]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
					}
				}
	
				$cats[$catKey]['url'] = URL_PREFIX . htmlspecialchars($cat['url']);
	      		$cats[$catKey]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	
				$subCategories = array_merge($subCats, $subCategories);
				if(!isset($subCategories["last_mod"]) || strtotime($subCategories["last_mod"]) < $subCat[0]['updated'])
				{
					$subCategories["last_mod"] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
				}
			}
			$categories = array_merge($cats, $categories);
	
			if(!isset($categories["last_mod"]) || strtotime($categories["last_mod"]) < $cats[0]['updated'])
			{
				$categories["last_mod"] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
			}
		}
      	$superCategories[$superKey]['url'] = URL_PREFIX . htmlspecialchars($supercat['url']);
      	$superCategories[$superKey]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
    }
	
	foreach ($pages as $key => $staticPage)
	{
		$staticPages[$key]['url'] = htmlspecialchars($staticPage['url']);
  		$staticPages[$key]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	}
	
	$pages["last_mod"] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	
	foreach ($articles as $key => $article)
	{
		$articles[$key]['url'] = URL_PREFIX ."articles/". htmlspecialchars($article['url']).".html";
  		$articles[$key]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	}
	$articles["last_mod"] = date_decode(date("c",  time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	
	foreach($products as $key => $product)
	{
		$products[$key]['date_updated'] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	}
	$products["last_mod"] = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
	
	$sitemapFiles["supercategories"] = generateSitemapFile($superCategories, '0.2');
	$sitemapFiles["static_pages"] = generateSitemapFile($staticPages, '0.4');
	$sitemapFiles["categories"] = generateSitemapFile($categories, '0.6');
	$sitemapFiles["articles"] = generateSitemapFile($articles, '1', "articles/");
	$sitemapFiles["products"] = generateSitemapFile($products, '1');

	foreach($sitemapFiles as $key => $value)
	{
		createSitemapFile($key, $value);
	}

	//$sitemapFiles["subcategories"] = generateSitemapFile($subCategories, '0.6');
	$sitemapIndex = generateSitemapIndex($sitemapFiles);

	createSitemapFile("sitemap_index", $sitemapIndex);

	print_r($sitemapIndex);

	function createSitemapFile($fileName, $content)
	{
		if(file_exists("../sitemaps/".$fileName.".xml"))
		{
			unlink("../sitemaps/".$fileName.".xml");
		}
		$file = fopen("../sitemaps/".$fileName.".xml", "wb");
		fwrite($file, $content);
		fclose($file);
	}
	function generateSitemapFile($items, $priority = "0.5", $urlPrefix = "")
	{
		if(count($items) == 0)
		{
	     	return NULL_SITEMAP;
		}
		$len = count($items);

		$lastMod = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
		if(isset($items["last_mod"]) && $items["last_mod"] != "")
		{
			$lastMod = $items["last_mod"];
			unset($items["last_mod"]);
		}

		$output = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
	  	$output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
		$output .=
			"<url>
			  <loc>{$urlPrefix}</loc>
			  <lastmod>{$lastMod}</lastmod>
			  <changefreq>weekly</changefreq>
			</url>";
		foreach($items as $item)
		{
			if(isset($item["url"]) && $item["url"] != "" && isset($item["date_updated"]) && $item["date_updated"] != "")
			{
				$output .= "
					<url>
					  <loc>{$item['url']}</loc>
					  <lastmod>{$item['date_updated']}</lastmod>
					  <priority>{$priority}</priority>
					</url>";
			}
		}
		$output .= "</urlset>";

		return $output;
	}

	function generateSitemapIndex($files)
	{
		$lastMod = date_decode(date("c", time()), SITE_TIMEZONE, W3C_DATETIME) . TIMEZONE_OFFSET;
		$output = '<?xml version="1.0" encoding="UTF-8"?>
					<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
		foreach($files as $key => $value)
		{
			$fileURL = URL_PREFIX."sitemaps/".$key.".xml";
			$output .= "
				<sitemap>
					<loc>{$fileURL}</loc>
					<lastmod>{$lastMod}</lastmod>
				</sitemap>";
		}

		$output .='</sitemapindex>';
		return $output;
	}

	function makeNodeURL($node)
	{
		$url = URL_PREFIX;
		switch ($node["type"])
		{
			case 'tour':
				$url .= "tur/".$node["id"]."/";
				break;
			case 'event':
				$url .= "eveniment/".$node["id"]."/";
				break;
			default:

				$nodeCategory = fetch_row("SELECT c.id,c.parent_id, cd.url_title AS url, c.level FROM categories c, category_details cd
											WHERE cd.category_id = c.id AND c.id = {$node["category_id"]} AND c.level = 2");

				if(!isset($nodeCategory["id"]))
				{
					return false;
				}

				$superCategory = fetch_row("SELECT c.id,c.parent_id, cd.url_title AS url, c.level FROM categories c, category_details cd
										WHERE cd.category_id = c.id AND c.id = {$nodeCategory["parent_id"]}");
				$url .= htmlspecialchars($superCategory["url"])."/".htmlspecialchars($nodeCategory["url"])."/";

				break;
		}
		$url .= htmlspecialchars($node['url']);

		return $url;
	}
?>

